<template>
  <i :class="svgClass" :style="inlineStyle" @mouseenter="enter" @mouseleave="leave" v-bind="$attrs">
    <img v-if="showImg" class="svg-icon" :class="className" :style="style" :src="iconName" :alt="iconName"/>
    <svg v-else class="svg-icon" :class="className" :style="style" aria-hidden="true">
      <use :xlink:href="iconName"></use>
    </svg>
  </i>
</template>
<script>
export default {
  name: 'GSvgIcon',
  props: {
    name: {
      type: String,
      default: ''
    },
    // ! deprecated
    hover: {
      type: Boolean,
      default: false
    },
    width: {
      type: [Number, String],
      default: 24
    },
    height: {
      type: [Number, String],
      default: 24
    },
    fill: {
      type: String
    },
    type: {
      type: String
    },
    disabled: Boolean
  },
  data() {
    return {
      inlineStyle: {},
      w: this.width,
      h: this.height,
      f: this.fill
    }
  },
  computed: {
    iconName() {
      if (this.showImg) {
        return this.name
      }
      return `#svg-${this.name}`
    },
    showImg() {
      return this.name.startsWith('https://') || this.name.startsWith('http://')
    },
    className() {
      return `icon-${this.name}`
    },
    style() {
      return {
        width: typeof this.w === 'number' ? this.w + 'px' : this.w,
        height: typeof this.h === 'number' ? this.h + 'px' : this.h,
        fill: this.f
      }
    },
    svgClass() {
      return [
        'g-svg-icon',
        this.type ? 'g-svg-icon--' + this.type : '',
        { 'is-disabled': this.disabled }
      ]
    }
  },
  watch: {
    width(val) {
      this.w = val
    },
    height(val) {
      this.h = val
    },
    fill(val) {
      this.f = val
    }
  },
  methods: {
    enter() {
      if (this.hover) {
        this.inlineStyle = {
          color: '#628cf5'
        }
      }
    },
    leave() {
      if (this.hover) {
        this.inlineStyle = {
          color: 'initial'
        }
      }
    }
  }
}
</script>
